#include "StdAfx.h"
#include "Utils.h"

#include <sstream>

namespace ftp
{
namespace utils
{

bool getCommandNameAndArgument(const std::string& str, std::string* cmdName, std::string* argument)
{
	//command have format <COMMAND NAME>[<SP><ARGUMENT>]<CR><LF>
	
	size_t crlfPos = str.find("\r\n");
	if (crlfPos == std::string::npos)
	{
		return false;
	}

	size_t spPos = str.find(' ');
	if (spPos == std::string::npos)
	{
		*cmdName = str.substr(0, crlfPos);
		*argument = "";
		return true;
	}

	*cmdName = str.substr(0, spPos);
	*argument = str.substr(spPos + 1, crlfPos - (spPos + 1));

	return true;
}

std::string makeCommonResponse(int resCode, const std::string& comment)
{
	std::ostringstream ostr;
	ostr << resCode << ' ' << comment << "\r\n";
	return ostr.str();
}

std::string makePwdResponse(int resCode, const std::string& dirPath, const std::string& comment)
{
	std::ostringstream ostr;
	ostr << resCode << " \"" << dirPath << "\" " << comment << "\r\n";
	return ostr.str();
}

std::string makePasvResponse(int resCode, const std::string& ip, const int port, const std::string& comment)
{
	std::string convertedIp = ip;
	std::replace(convertedIp.begin(), convertedIp.end(), '.', ',');
	
	std::ostringstream ostr;
	ostr << resCode << " " << convertedIp << "," << ((port >> 8) % 0xff) << "," << (port % 0xff) << " " << comment << "\r\n";

	return ostr.str();
}

}
}